package com.jfire.baseutil.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import com.jfire.baseutil.collection.ByteCache;
import com.jfire.baseutil.collection.StringCache;

public class SimpleHttpTool
{
    private static ThreadLocal<ByteCache>   cacheLocal  = new ThreadLocal<ByteCache>() {
        protected ByteCache initialValue()
        {
            return new ByteCache();
        }
    };
    private static ThreadLocal<StringCache> stringLocal = new ThreadLocal<StringCache>() {
        protected StringCache initialValue()
        {
            return new StringCache();
        }
    };
    
    /**
     * 进行http get请求，并且将读取的返回字节编码后返回
     * 
     * @param url
     * @param charset
     * @return
     */
    public static String get(String url, Charset charset)
    {
        HttpURLConnection httpUrlConn;
        try
        {
            httpUrlConn = (HttpURLConnection) new URL(url).openConnection();
        }
        catch (IOException e1)
        {
            throw new RuntimeException(e1);
        }
        try
        {
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            ByteCache cache = cacheLocal.get();
            cache.clear();
            cache.ensureCapacity(1024);
            int readSum = -1;
            while ((readSum = inputStream.read(cache.getDirectArray(), cache.getCount(), 1000)) != -1)
            {
                cache.setCount(cache.getCount() + readSum);
                cache.ensureCapacity(1000);
            }
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            return cache.toString(charset);
        }
        catch (IOException e)
        {
            httpUrlConn.disconnect();
            throw new RuntimeException(e);
        }
        
    }
    
    /**
     * 进行post请求，并且将返回结果以编码形式得到
     * 
     * @param url
     * @param charset
     * @param map
     * @return
     */
    public static String post(String url, Charset charset, Map<String, String> map)
    {
        HttpURLConnection httpUrlConn;
        try
        {
            httpUrlConn = (HttpURLConnection) new URL(url).openConnection();
        }
        catch (IOException e1)
        {
            throw new RuntimeException(e1);
        }
        try
        {
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("POST");
            ByteCache cache = cacheLocal.get().clear();
            OutputStream outputStream = httpUrlConn.getOutputStream();
            if (map != null)
            {
                outputStream.write(buildParam(map).getBytes(charset));
            }
            InputStream inputStream = httpUrlConn.getInputStream();
            cache.clear();
            cache.ensureCapacity(1024);
            int readSum = -1;
            while ((readSum = inputStream.read(cache.getDirectArray(), cache.getCount(), 1000)) != -1)
            {
                cache.setCount(cache.getCount() + readSum);
                cache.ensureCapacity(1000);
            }
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            return cache.toString(charset);
        }
        catch (IOException e)
        {
            httpUrlConn.disconnect();
            throw new RuntimeException(e);
        }
    }
    
    private static String buildParam(Map<String, String> map)
    {
        StringCache stringCache = stringLocal.get();
        stringCache.clear();
        boolean append = false;
        for (Entry<String, String> each : map.entrySet())
        {
            if (each.getValue() != null)
            {
                stringCache.append(each.getKey()).append('=').append(each.getValue()).append('&');
                append = true;
            }
        }
        if (append)
        {
            stringCache.deleteLast();
        }
        return stringCache.toString();
    }
    
    /**
     * 向url地址post方式发送一段文本信息
     * 
     * @param url
     * @param postStr
     * @param charset
     * @return
     */
    public static String post(String url, String postStr, Charset charset)
    {
        HttpURLConnection httpUrlConn;
        try
        {
            httpUrlConn = (HttpURLConnection) new URL(url).openConnection();
        }
        catch (IOException e1)
        {
            throw new RuntimeException(e1);
        }
        try
        {
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("POST");
            ByteCache cache = cacheLocal.get().clear();
            httpUrlConn.getOutputStream().write(postStr.getBytes(charset));
            httpUrlConn.getOutputStream().flush();
            InputStream inputStream = httpUrlConn.getInputStream();
            cache.clear();
            cache.ensureCapacity(1024);
            int readSum = -1;
            while ((readSum = inputStream.read(cache.getDirectArray(), cache.getCount(), 1000)) != -1)
            {
                cache.setCount(cache.getCount() + readSum);
                cache.ensureCapacity(1000);
            }
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            return cache.toString(charset);
        }
        catch (IOException e)
        {
            httpUrlConn.disconnect();
            throw new RuntimeException(e);
        }
    }
    
    public static String getIp()
    {
        try
        {
            String text = SimpleHttpTool.get("http://1111.ip138.com/ic.asp", Charset.forName("gb2312"));
            int left = text.indexOf('[');
            int right = text.indexOf(']');
            return text.substring(left + 1, right);
        }
        catch (Exception e)
        {
            return null;
        }
    }
    
    public static void main(String[] args)
    {
        
        System.out.println(SimpleHttpTool.post("http://192.168.40.11:4568", Charset.forName("utf-8"), null));
    }
}
